package reading;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.system.ApplicationPidFileWriter;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import reading.common.constant.SpecialStringConstant;
import reading.common.setting.AsSetting;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * @author TXW
 * @version V1.0
 * @Title: ${file_name}
 * @date 2018/9/17 16:11
 */
@ComponentScan
@EnableCaching
@SpringBootApplication
@EnableScheduling
public class Application {

    @Autowired
    private AsSetting asSetting;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.addListeners(new ApplicationPidFileWriter("app.pid"));
        app.run(args);
    }

    /**
     * 设置服务器文件上传限制
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大 KB,MB
        factory.setMaxFileSize("102400KB");
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        /**
         * 设置上传路径
         * 如果未设置上传路径
         * 框架会指定一个默认路径
         * 但是有时候默认路径会创建失败
         * The temporary upload location [/tmp/tomcat.240988458284008338.28080/work/Tomcat/localhost/ROOT] is not valid
         *
         * 所以，需要预先设置一个指定的临时路径
         *
         * 2017-10-10日Bug
         */
        String location = "";
        if (System.getProperty(SpecialStringConstant.OS_NAME).toLowerCase().startsWith(SpecialStringConstant.WIN)) {
            //解决Windows下报以上的错误！
            location = "/";
        } else {
            String tempPath = asSetting.getFileUploadTempPath();
            location = StringUtils.isBlank(tempPath) ? "/data/school/upload" : tempPath;
            File file = new File(location);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}